package Util;

import java.sql.*;

/*
核心类 负责处理java与数据库的访问
负责CURD操作
 */
public class SQLUtil {

    public static final String url = "jdbc:mysql://127.0.0.1:3306/online_selection_course?characterEncoding=utf8&serverTimezone=GMT%2B8";
    public static final String user = "root";
    public static final String password = "admin";

    private Connection connection = null;
    private PreparedStatement pstm = null;


    public void init() {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");

            connection = DriverManager.getConnection(url, user, password);

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    public Connection getConnect() {
        if (connection == null) {
            init();
        }
        return connection;
    }

    public  void setObject(Object object[]){
        if (pstm!=null && object!=null){
            for (int i = 0; i < object.length; i++) {
                try {
                    pstm.setObject(i + 1, object[i]);
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }

    }


    public int execute(String sql, Object[] object) {

        try {
            connection = getConnect();
            pstm = connection.prepareStatement(sql);


            setObject(object);
            pstm.execute();

            return pstm.getUpdateCount();


        } catch (SQLException e) {
            e.printStackTrace();
        }
//        } finally {
//            try {
//                if (pstm != null) pstm.close();
//                if (connection != null) connection.close();
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
        return 0;
    }


    public ResultSet executeQuery(String sql, Object object[]) {

        try {

            connection = getConnect();
            pstm = connection.prepareStatement(sql);

            setObject(object);

            return pstm.executeQuery();


        } catch (SQLException e) {
            e.printStackTrace();
        }
//        } finally {
//            try {
//                if (pstm != null) pstm.close();
//                if (connection != null) connection.close();
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
        return null;
    }

}
